/**
 * @file    Expression classname is undefined on line 2, column 15 in Templates/Classes/Class.java.
 * @author  Haseeb Yousaf
 * @see     LICENSE (MIT style license file)
 * @version 1.0
 * @date    Nov 15, 2011 8:44:30 PM
 */
package carrello.model.association;

import java.util.List;
import carrello.util.EntityManagerUtil;
import java.util.List;
import carrello.model.entities.Category;
import carrello.model.entities.Product;
import carrello.util.EntityManagerUtil;
import java.util.Set;
import static carrello.util.EntityManagerUtil.getEntityManager;

public class ProductBelongsToCategory implements AbstractAssociation{
    private Category category;
    private Set<Product> products;
    private Product product;
    
    public ProductBelongsToCategory()
    {}
    
    public ProductBelongsToCategory(Category category, Set<Product> products)
    {
        this.category = category;
        this.products = products;
    }
    
    public ProductBelongsToCategory(Category category, Product product)
    {
        this.category = category;
        this.product = product;
    }
    /**
     * Saves a many to one association 
     */
    public void saveAll() 
    {
        getEntityManager().beginUnitOfWork();
        this.category.setProduct(this.products);
        for ( Product p : products)
        {
           p.setCategory(this.category);
           getEntityManager().update(p);
        }
        getEntityManager().update(category);
        getEntityManager().endUnitOfWork();
    }
    
    /**
     * deletes the association 
     */
    public void deleteAll() 
    {
        
        for (Product p : products) {
            new AttributeValue().delete(p);
        }
        
//        getEntityManager().removeAll(category.getAttribute());
        getEntityManager().removeAll(products);
//       
//        getEntityManager().endUnitOfWork();
    }
    
    public void delete() {}
    /**
     * updates the association
     */
    public void update() {}
    /**
     * saving a one to one relationship
     */
    public void save()
    {
        getEntityManager().beginUnitOfWork();
        product.setCategory(category);
        getEntityManager().store(product);
        getEntityManager().store(category);
        getEntityManager().beginUnitOfWork();
    }
    public static List<Product> getProductByCategoryName(String catName){
        List<Product> plist = EntityManagerUtil.getHqlQuery("select c.product from Category c where c.name =:cname ").setParameter("cname", catName).list();
       return plist;
    }
    
//    public static void main(String[] args)
//    {
//        List plist = new ProductBelongsToCategory().getProductfromCat("Books");
//        System.out.println(plist);
//    }
}
